#!/bin/bash

source /usr/local/emhttp/plugins/compose.manager/default.cfg
source /boot/config/plugins/compose.manager/compose.manager.cfg

COMPOSE_ROOT=$PROJECTS_FOLDER
COMPOSE_WRAPPER=/usr/local/emhttp/plugins/compose.manager/scripts/compose.sh

for dir in $COMPOSE_ROOT/*; do
    if [ -d "$dir" ]; then
        if [ -f "$dir/docker-compose.yml" ] || [ -f "$dir/indirect" ]; then
            name=${dir}/name
            name=$(< "${name}")
            override=""
            if [ -f "$dir/docker-compose.override.yml" ]; then
                override="$dir/docker-compose.override.yml"
                override="-f ${override@Q}"
            fi
            envpath=""
            if [ -f "$dir/envpath" ]; then
                envpath="$dir/envpath"
                envpath="$(< "${envpath}" )"
                envpath="-e ${envpath@Q}"
            fi
            logger "Stopping compose stack: ${name// /_}"
            if [ -f "$dir/indirect" ]; then
                indirect=${dir}/indirect
                indirect=$(< "${indirect}")
                eval $COMPOSE_WRAPPER -c stop -d ${indirect@Q} -p "${name// /_}" $override $envpath > /dev/null &
            else
                dir="$dir/docker-compose.yml"
                eval $COMPOSE_WRAPPER -c stop -f ${dir@Q} -p "${name// /_}" $override $envpath > /dev/null &
            fi
        fi
    fi
done

wait
